<?php

namespace app\admin\business;

use think\Exception;

class AdminUser
{
    /**
     * 判断登陆
     * @param $data
     * @return bool
     * @throws Exception
     * User: xyb
     * Date: 2023/3/5 09:03
     */
    public static function login($data)
    {
        try {
            $adminUserModel = new \app\common\model\mysql\AdminUser();
            $adminUser = self::getAdminUserByUsername($data['username']);
            if (empty($adminUser)) {
                throw new Exception("不存在该用户或状态异常");
            }
            if ($adminUser['password'] != md5("admin_xu_" . $data['password'])) {
                throw new Exception("密码不正确");
//                return show(config("status.error"), "密码不正确");
            }//记录信息到mysql
            $data = [
                'update_time' => time(),
                'last_login_time' => time(),
                'last_login_ip' => request()->ip(),
                'operate_user' => $adminUser['username']
            ];
            $updateData = $adminUserModel->updateById($adminUser['id'], $data);
            if (empty($updateData)) {
                throw new Exception("更新数据失败");
//                return show(config("status.error"), "更新数据失败");
            }

        } catch (\Exception $e) {
            // todo 记录日志 $e->getMessage()
            \think\facade\Log::error('登录异常：' . $e->getMessage());
            throw new Exception("内部异常，登陆失败");
        }
        // 记录session
        session(config("admin.session_admin"), $adminUser);

        return true;

    }

    /**
     * 根据用户名获取用户信息
     * @param $username
     * @return array|false
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * User: xyb
     * Date: 2023/3/5 09:01
     */
    public static function getAdminUserByUsername($username)
    {
        $adminUserModel = new \app\common\model\mysql\AdminUser();
        $adminUser = $adminUserModel->getAdminUserByUsername($username);//        dump($adminUser->status);exit();
        if (empty($adminUser)) {
            return false;
        }
        if (empty($adminUser['username']) || $adminUser['status'] != config("status.mysql.table_normal")) {
            return false;
//                return show(config("status.error"), "用户不存在");
        }
        return $adminUser->toArray();
    }
}